<?php
class DB_Manager implements DB_Manager_Interface {

    private $_objConfig = null;


    private $_arDBs = array();


    private $_arDbReaders = array();


    private $_arDbCurds = array ();


    /**
     * @return Config_Interface
     */
    private function getConfig () {
        return $this->_objConfig;
    }


    public function __construct(Config_Interface $objConfig) {
        $this->_objConfig = $objConfig;
    }


    public function includeMysqlDbSimple () {
        $strPathToLibrary = $this->getConfig()->getAttribute('FW_PATHS', 'LIBRARY');
        require_once $strPathToLibrary.'/dbsimple/DbSimple/lib/DbSimple/Mysql.php';
    }


    /**
     * @param string $strDbName
     * @param string $strCharset
     * @return DbSimple_Generic_Database
     */
    public function getDb($strDbName, $strCharset = 'utf8') {
        if (!isset($this->_arDBs[$strDbName])) {
            $dsn = $this->getConfig()->getAttribute('DB', $strDbName);
            $this->_arDBs[$strDbName] = new DbSimple_Mysql($dsn);
            $this->_arDBs[$strDbName]->setErrorHandler(array($this,'dbErrorHandler'));

        }
        $this->_arDBs[$strDbName]->query('SET NAMES ?', $strCharset);
        return $this->_arDBs[$strDbName];
    }


    public function dbErrorHandler ($message, $info) {
        throw new Exception($message.' '.$info);
    }

    /**
     * @param string $strTableName
     * @param string $strId
     * @param string $strCharset
     * @return DB_Reader
     */
    public function getDbReader($strDbName, $strTableName, $strId = 'id', $strCharset = 'utf8'){
        if (!isset($this->_arDbReaders[$strDbName][$strTableName])) {
            $this->_arDbReaders[$strDbName][$strTableName] =
                new DB_Reader($this->getDb($strDbName, $strCharset), $strTableName, $strId);
        }
        return $this->_arDbReaders[$strDbName][$strTableName];
    }


    /**
     * @param string $strTableName
     * @param string $strId
     * @param string $strCharset
     * @return DB_Curd
     */
    public function getDbCurd ($strDbName, $strTableName, $strId = 'id', $strCharset = 'utf8') {
        if (!isset($this->_arDbCurds[$strDbName][$strTableName])) {
            $this->_arDbCurds[$strDbName][$strTableName] =
                new DB_Curd($this->getDb($strDbName, $strCharset), $strTableName, $strId);
        }
        return $this->_arDbCurds[$strDbName][$strTableName];
    }
}